package uk.co.richardwkirk.parkrun.android.dataload;

import uk.co.richardwkirk.parkrun.android.IntentExtras;
import uk.co.richardwkirk.parkrun.android.R;
import android.app.Activity;
import android.app.LoaderManager;
import android.content.Intent;
import android.content.Loader;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class LoadDataDisplay extends Activity implements LoaderManager.LoaderCallbacks<LoadableParkrunDataAdapter> {

	String loadType = null;
	String loadId = null;
	boolean reload = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.load_data);

		// Get the type of event data we are loading
		Intent intent = getIntent();
		loadType = intent.getStringExtra(IntentExtras.EXTRA_DATA_LOAD_TYPE);
		reload = intent.getBooleanExtra(IntentExtras.EXTRA_DATA_LOAD_FORCE_RELOAD, false);
		loadId = intent.getStringExtra(IntentExtras.EXTRA_DATA_LOAD_ID);
		TextView loadDataCaption = (TextView) findViewById(R.id.load_data_caption);
		loadDataCaption.setText("Loading " + loadType + "...");
		
		// Start a loader to load the parkrun event data
		getLoaderManager().initLoader(0, null, this);
	}


	@Override
	public Loader<LoadableParkrunDataAdapter> onCreateLoader(int id, Bundle args) {
		ParkrunDataLoader loader = null;
		if (IntentExtras.DATA_LOAD_TYPE_EVENT_DATA.equals(loadType)) {
			Log.v("PARKRUN", "Creating a loader to get the parkrun event data.");
			loader = new WorldEventLoader(getApplicationContext());
		}
		else if (IntentExtras.DATA_LOAD_TYPE_NEWS_FEED.equals(loadType)) {
			Log.v("PARKRUN", "Creating a loader to get the parkrun news feed: " + loadId);
			loader = new NewsLoader(getApplicationContext(), loadId);
		}
		else if (IntentExtras.DATA_LOAD_TYPE_ATHLETE_DATA.equals(loadType)) {
			Log.v("PARKRUN", "Creating a loader to get athlete data: " + loadId);
			loader = new AthleteSummaryDataLoader(getApplicationContext(), loadId);
		}
		loader.setForceReload(reload);
		return loader;
	}

	@Override
	public void onLoadFinished(Loader<LoadableParkrunDataAdapter> loader, LoadableParkrunDataAdapter parkrunData) {
		// Return that the data has been loaded
		Intent data = new Intent();
		if (parkrunData != null) {
			parkrunData.completeLoad();
			setResult(RESULT_OK, data);
		}
		else {
			setResult(RESULT_CANCELED, data);
		}
		finish();
	}

	@Override
	public void onLoaderReset(Loader<LoadableParkrunDataAdapter> arg0) {
		// Nothing required.
	}

}

